/**
 * File Comment: server side doctor session
 */
package edu.gatech.oad.project.networking.serverSessions; // $codepro.audit.disable packageNamingConvention

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import edu.gatech.oad.project.coordinator.Office;
import edu.gatech.oad.project.networking.Session;
import edu.gatech.oad.project.networking.messages.Message;
import edu.gatech.oad.project.operations.users.Doctor;

/**
 * Server side doctor session
 * 
 * @author James Moore
 * @version 1.0
 */
public class DoctorSession extends Session {

    /**
     * Field myLogger: holds the logger for the office file
     */
    private static final Logger MYLOGGER = Logger.getLogger("edu.gatech." +
            "oad.project.networking.serverSessions");
    
    /**
     * Default constructor
     * 
     * @param doc active user
     * @param token security token
     * @param client connection
     * @param outBound stream to the client
     * @param inBound stream from the client
     */
    public DoctorSession(Doctor doc, long token, 
            Socket client, ObjectOutputStream outBound, ObjectInputStream inBound){
        super(doc, token, client, outBound, inBound);
        
        MYLOGGER.addHandler(Office.FILEHANDLER);
        MYLOGGER.setLevel(Level.ALL);
    }
    
    /**
     * Executed when thread starts
     */
    @Override
    public void run() {
        Message mess;
        try {
            mess = (Message) this.inBound.readUnshared();
            
            while(mess != null) {
                if(mess.getToken() == this.token) {
                    Message response = mess.handle();
                    this.outBound.writeUnshared(response);
                    this.outBound.flush();
                }
                
                mess = (Message) this.inBound.readUnshared();
            }
                
        } catch (IOException e) {

            MYLOGGER.severe("" + e);
        } catch (ClassNotFoundException e) {

            MYLOGGER.severe("" + e);
        }
        finally {
            try {
                this.outBound.close();
                this.inBound.close();
                this.client.close();
            } catch (IOException e) {
                
                MYLOGGER.severe("" + e);
            }

        }
    }

    /**
     * @return a string
     */
    @Override
    public String toString() {
        return "DoctorSession [user=" + user + ", id=" + id + ", token="
                + token + ", client=" + client + ", outBound=" + outBound
                + ", inBound=" + inBound + "]";
    }
    

}